/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.dianlan.processor.business;

import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.component.gateway.dianlan.annotations.DianlanProtocolParse;
import info.peigen.hotpot.component.gateway.dianlan.facade.command.order.DianlanHeartOrder;
import info.peigen.hotpot.component.gateway.dianlan.facade.command.result.DianlanHeartResult;
import info.peigen.hotpot.component.gateway.dianlan.facade.enums.DianlanFrameSign;
import info.peigen.hotpot.component.gateway.dianlan.processor.AbstractDianlanProcessor;
import info.peigen.hotpot.component.gateway.dianlan.protocol.Dianlan;
import info.peigen.hotpot.component.gateway.dianlan.protocol.passive.DianlanHeartBeat;
import info.peigen.hotpot.component.gateway.dianlan.protocol.passive.DianlanHeartBeatResponse;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.smartboot.socket.MessageProcessor;
import org.smartboot.socket.StateMachineEnum;
import org.smartboot.socket.transport.AioSession;

/**
 * <b>(DianlanHeartProcessor)</b>
 *
 * @author czj
 * @version 1.0.0
 * @since 2022/11/17
 */
@Component("dianlanHeartProcessor")
@Slf4j
public class DianlanHeartProcessor<T> extends AbstractDianlanProcessor implements MessageProcessor<T> {

    @Override
    public void process(AioSession session, Object obj) {
        Dianlan          dianlan   = (Dianlan) obj;
        DianlanHeartBeat heartBeat = DianlanProtocolParse.deserialization(dianlan.getData(), DianlanHeartBeat.class);
        if (StrUtil.equals(heartBeat.getChargingPortNo(), IGNORE_PORT)) {
            ignorePort(dianlan);
            return;
        }
        DianlanHeartOrder order = DianlanHeartOrder.builder()
                .chargingStatus(heartBeat.getChargingStatus())
                .sessionId(session.getSessionID())
                .stubNo(heartBeat.getStubNo())
                .build();
        DianlanHeartResult result = dianlanServiceFacade.heart(order);
        if (result.success()) {
            DianlanHeartBeatResponse response = DianlanHeartBeatResponse.builder()
                    .stubNo(heartBeat.getStubNo())
                    .chargingPortNo(heartBeat.getChargingPortNo())
                    .build();
            response(dianlan, response);
            dianlan.setFrameSign(DianlanFrameSign.HeartBeatResponse);
            write(session, dianlan);
            // log.info("收到心跳：" + JSON.toJSONString(heartBeat) + ",应答：" + JSON.toJSONString(response));
        } else {
            log.info("心跳内部逻辑失败。");
        }
    }

    @Override
    public void stateEvent(AioSession session, StateMachineEnum stateMachineEnum, Throwable throwable) {
        MessageProcessor.super.stateEvent(session, stateMachineEnum, throwable);
    }
}